<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="head-container">
          <SaOrgTree @node-click="orgTreeNodeClick"/>
        </div>
      </el-col>
      <el-col :span="18">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-radio-group v-model="tableView" size="small" @change="refreshMenuTable">
              <el-radio-button label="role">角色</el-radio-button>
              <el-radio-button label="permission">权限</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-if="!!currentSelectedOrg.id"
                       v-hasPermi="['sa:authorize:create']">分配
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">
                      <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                                 :loading="exportLoading"
                                 v-hasPermi="['sa:authorize:export']">导出
                      </el-button>
                    </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="refreshMenuTable"></right-toolbar>
        </el-row>

        <!-- 列表 -->
        <el-table v-if="tableView == 'role'"
                  max-height="540"
                  v-loading="loading"
                  :data="list">
          <el-table-column label="编码" align="center" prop="code"/>
          <el-table-column label="角色" align="center" prop="name"/>
          <el-table-column label="是否继承" align="center" prop="orgFullId">
            <template v-slot="scope">
              <span>{{ filterIsParentRole(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否排除" align="center" prop="orgFullName">
            <template v-slot="scope">
              <span>{{ scope.row.parentExcluded == '0' && scope.row.myselfExcluded == '0' ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建日期" align="center" prop="createTime" width="180">
            <template v-slot="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                         v-if="!isParentRole(scope.row)"
                         v-hasPermi="['sa:authorize:delete']">删除
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleExcluded(scope.row)"
                         v-if="isParentRole(scope.row) && scope.row.myselfExcluded == '0' && scope.row.parentExcluded == '0'"
                         v-hasPermi="['sa:authorize:exclude']">排除
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCancelExcluded(scope.row)"
                         v-if="scope.row.myselfExcluded != '0'"
                         v-hasPermi="['sa:authorize:exclude']">不排除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination v-show="total > 0 && tableView == 'role'" :total="total" :page.sync="queryParams.pageNo"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <!--        权限-->
        <el-table v-if="tableView == 'permission' && refreshTable"
                  v-loading="loading"
                  max-height="540"
                  :data="menuList"
                  row-key="menuId"
                  :default-expand-all="isExpandAll"
                  :default-sort="{prop: 'sort'}"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" width="250"></el-table-column>
          <el-table-column prop="icon" label="图标" align="center" width="50">
            <template v-slot="scope">
              <svg-icon :icon-class="scope.row.icon"/>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="50"></el-table-column>
                    <el-table-column prop="permission" label="权限标识" :show-overflow-tooltip="true"/>
          <!--          <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"/>-->
<!--                    <el-table-column prop="componentName" label="组件名称" :show-overflow-tooltip="true"/>-->

        </el-table>


      </el-col>
    </el-row>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" height="500px" v-dialogDrag append-to-body>
      <SaRolePicker @select-change="roleSelectChanged"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createAuthorize,
  deleteAuthorize,
  getAuthorize,
  getAuthorizePage,
  exportAuthorizeExcel,
  excludedAuthorize,
  cancelExcludedAuthorize
} from "@/api/sa/authorize";
import {
  getPermissionList
} from "@/api/sa/permission";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import SaOrgTree from '@/components/SaOrgTree';
import SaRolePicker from '@/components/SaRolePicker';

export default {
  name: "Authorize",
  components: {
    SaOrgTree,
    SaRolePicker
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      tableView: 'role',
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色授权 列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 机构搜索
      orgName: '',
      orgOptions: undefined,
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        orgId: null,
        orgName: null,
        orgFullId: null,
        orgFullName: null,
        roleId: null,
        version: null,
      },
      currentSelectedOrg: {},
      // 表单参数
      form: {},
      selectedRoles: [],

      //权限
      menuList: [],
      isExpandAll: true,
      refreshTable: true
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 角色是否继承
    filterIsParentRole(row) {
      return row.orgId == this.currentSelectedOrg.id ? '否' : '是'
    },
    // 角色是否继承
    isParentRole(row) {
      return row.orgId != this.currentSelectedOrg.id
    },
    // 角色是否继承
    isMyselfExclude(row) {
      return row.myselftExclude != this.currentSelectedOrg.id
    },
    // 节点单击事件
    orgTreeNodeClick(data) {
      this.currentSelectedOrg = data
      this.queryParams.orgFullId = data.fullId;
      this.getList();
      this.getMenuList()
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getAuthorizePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        orgId: undefined,
        orgName: undefined,
        orgFullId: undefined,
        orgFullName: undefined,
        roleId: undefined,
        version: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色授权 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getAuthorize(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改角色授权 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.selectedRoles || this.selectedRoles.length == 0) {
        this.$modal.msgError("请选择角色")
        return
      }

      let roleIds = []
      this.selectedRoles.forEach(role => {
        roleIds.push(role.id)
      })
      this.form.roleId = roleIds.join(",")
      this.form.orgId = this.currentSelectedOrg.id
      this.form.orgName = this.currentSelectedOrg.name
      this.form.orgFullId = this.currentSelectedOrg.fullId
      this.form.orgFullName = this.currentSelectedOrg.fullName
      createAuthorize(this.form).then(response => {
        this.$modal.msgSuccess("分配成功");
        this.open = false;
        this.getList();
        this.getMenuList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.name;
      const id = row.id;
      this.$modal.confirm('是否确认删除角色 名称为"' + name + '"的数据项?').then(function () {
        return deleteAuthorize(id);
      }).then(() => {
        this.getList();
        this.getMenuList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 排除角色权限 按钮操作 */
    handleExcluded(row) {
      const roleName = row.name;
      const orgName = this.currentSelectedOrg.name
      const id = row.roleId;
      const orgFullId = this.currentSelectedOrg.fullId
      this.$modal.confirm('是否确认排除机构"' + orgName + '"继承的角色"' + roleName + '"的数据项?').then(function () {
        return excludedAuthorize(id, orgFullId);
      }).then(() => {
        this.getList();
        this.getMenuList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    },
    /** 取消排除角色权限 按钮操作 */
    handleCancelExcluded(row) {
      const roleName = row.name;
      const orgName = this.currentSelectedOrg.name
      const id = row.roleId;
      const orgFullId = this.currentSelectedOrg.fullId
      this.$modal.confirm('是否确认不排除角色授权 名称为"' + roleName + '"的数据项?').then(function () {
        return cancelExcludedAuthorize(id, orgFullId);
      }).then(() => {
        this.getList();
        this.getMenuList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有角色授权 数据项?').then(() => {
        this.exportLoading = true;
        return exportAuthorizeExcel(params);
      }).then(response => {
        this.$download.excel(response, '角色授权 .xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    roleSelectChanged(data) {
      this.selectedRoles = data
    },

    changeTableView(val) {
      if (val == 'permission') {
        this.refreshMenuTable()
      }
    },
    // 渲染表格树
    refreshMenuTable() {
      if (this.tableView == 'permission') {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      }

    },
    /** 查询权限列表 */
    getMenuList() {
      this.loading = true;
      // 执行查询
      getPermissionList(this.currentSelectedOrg.fullId).then(response => {
        this.menuList = this.handleTree(response.data, "menuId", undefined, undefined, 0);
        this.refreshMenuTable()
        this.loading = false;
      });
    },
  }
};
</script>
<style scoped>
.tree-height {
  height: 400px;
  overflow-y: scroll
}
</style>
